package controller;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import pojo.User;
import service.UserService;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private Result result;
    //查询条件
    private User condition;


    //分页显示数据处理器
    @RequestMapping("/userlist")
    public ModelAndView userlist(ModelAndView mv, @RequestParam(defaultValue = "1") int pageNum) {
        PageInfo pageInfo = userService.queryByPage(pageNum, condition);
        List<User> list = pageInfo.getList();
        mv.addObject("list", list);//数据model封装翻页数据
        mv.addObject("page", pageInfo);//数据model封装翻页信息
        mv.setViewName("admin/userlist");
        return mv;
    }


    //userserch处理器
    @RequestMapping("/usersearch")
    public String usersearch(User user) {
        condition = user;
        return "redirect:/admin/userlist";//重定向到userlist,不经过视图解析器
    }


    //userdel处理器
    @RequestMapping("/userdel")
    public ModelAndView userdel(ModelAndView mv, String userid) {
        boolean rs = userService.removeuser(userid);
        if (rs) {//删除成功
            result.setOk(true);
            result.setInfo("删除成功!");
            result.setHref("/admin/userlist");
        } else {//删除失败
            result.setOk(false);
            result.setInfo("删除失败!");
            result.setHref("javascript:history.back(-1)");
        }
        //封装数据模型
        mv.addObject("result", result);
        //封装视图
        mv.setViewName("admin/message");
        return mv;
    }

    //useradd处理器
    @RequestMapping("/useradd")
    public ModelAndView useradd(ModelAndView mv, User user) {
        boolean flag = userService.adduser(user);
        if (flag) {//添加成功
            result.setOk(true);
            result.setInfo("添加成功!");
            result.setHref("/admin/userlist");
        } else {//添加失败
            result.setOk(false);
            result.setInfo("添加失败!");
            result.setHref("javascript:history.back(-1)");
        }
        //封装数据模型
        mv.addObject("result", result);
        //封装视图
        mv.setViewName("admin/message");
        return mv;
    }

    //checkuserid处理器
    @RequestMapping("/checkuserid")
    @ResponseBody//加注释响应体:设置回显数据为string型,不经过视图解析器
    public String checkuserid(String userid) {
        User user = userService.queryuser(userid);
        if (user != null) {//占用
            return "用户ID已经被占用！";
        } else {//未占用
            return "";
        }
    }

}
